package org.keeners.imageviewer {	
	
	/*
		handles hit highlighting
	*/
	
	import flash.external.ExternalInterface;	
    import flash.net.URLRequest;
    import flash.net.URLLoader;
	import flash.events.* ;
	
	import com.adobe.serialization.json.JSON;
	
	public class ImageOcr{
		
		private var _config:Config;
		private var _base:ImageViewerBase;
		
		public function ImageOcr(config:Config, base:ImageViewerBase):void{
			_config = config;
			_base = base;
		}
				
		public function load_ocr(args:Object):void{
			/*
				get ocr object into config
			*/
			
			ExternalInterface.call("keenerview.handle_event", "ocr_load_start");
			
			if (_config.ocr_url){
				json_connect(_config.ocr_url)
			}else if(_config.ocr_data){
				_config.ocr = JSON.decode(_config.ocr_data).ocr;
				handle_ocr();
			}
			
		}
		
		
		public function json_connect (ocr_url) {        	            
            var loader:URLLoader = new URLLoader() ;
            var request:URLRequest = new URLRequest() ;                        
            request.url = ocr_url;
            loader.load(request);                        
            loader.addEventListener(Event.COMPLETE, function json_decode(event:Event):void {
		        	var loader:URLLoader = URLLoader(event.target) ;
		        	_config.ocr = JSON.decode(loader.data).ocr ;   
		        	handle_ocr();
		        }            
            ) ;
            
        }
        
       	public function handle_ocr():void {
       		
        	// _base.loaded - avoid race condition
        	if (_config.ocr_query && _base.loaded == true){
				hit_highlight(_config.ocr_query);	
        	}
        	
        	ExternalInterface.call("keenerview.handle_event", "ocr_load_complete");
        	
        }
        
        public function hit_highlight(query:String):void {
        	
        	var hits:Object = {};
        	
        	if(_config.ocr_query_url){
        		var loader:URLLoader = new URLLoader() ;
	            var request:URLRequest = new URLRequest();        
	            request.url = _config.ocr_query_url + 'query=' + escape(query);
	            loader.load(request);
	            loader.addEventListener(Event.COMPLETE, function json_decode(event:Event):void {
			        	var loader:URLLoader = URLLoader(event.target);
			        	hits = JSON.decode(loader.data);
			        	_base.draw_highlights(hits);
			        }            
	            );
	            return;
        	}
        	
        	       		
       		var ocr_text:String = _config.ocr.text;
       		var ocr_positions:Array = _config.ocr.positions;
       		var query_split = query.split(';');
       		
       		var re_query:RegExp;
       		var result:Object;
       		var start_index:int;
       		var end_index:int;       		
       		var i:int;
       		
       		if (_config.ocr_search_algorithm == 'border_any'){
       			
       			// border anything (get hits, then rewrite the indices if its in the middle)
       			
       			re_query = new RegExp('('+query_split.join('|')+')', "gi");				
	       		result = re_query.exec(ocr_text);	       		      
		        while (result != null) {
		             trace('hit: ', result.index, " ", result[1]);
		             var result1_index:int = result.index
		             hits[result1_index] = {index:result1_index, match:result[1], box:[]}
		             result = re_query.exec(ocr_text);
		        }
		        
		        var hits_redux:Object = {}
	       		for (i=0;i<ocr_positions.length;i++){
	       			start_index = ocr_positions[i][1][0];
	       			end_index = ocr_positions[i][1][1];
	       			for (var hit_index in hits){
	       				var key_as_number:Number = Number(hit_index);
	       				if (start_index <= key_as_number && key_as_number <= end_index){
	       					hits_redux[start_index] = hits[hit_index];	       					
	       					hits_redux[start_index].box = ocr_positions[i][0];
	       					trace(hits_redux[start_index])
	       				}
	       			}
	       		}
	       		hits = hits_redux;
       			
       		}else{
       			
       			// border non-alphanumeric only, border_default start only, border_exact must cleanly border start and end
       			
	       		re_query = new RegExp('(^|\\W)('+query_split.join('|')+')' + (_config.ocr_search_algorithm == 'border_exact' ? '(s|es)?($|\\W)' : ''), "gi"); //\\W(s|es)?	       		
	       		result = re_query.exec(ocr_text);	        
		        while (result != null) {
		             trace('hit: ', result.index, " ", result[1]);
		             // result1_length to account for \W leading character
		             var result1_length:int = result[1].length
		             var result2_index:int = result.index + result1_length
		             hits[result2_index] = {index:result2_index, match:result[2], box:[]}
		             result = re_query.exec(ocr_text);
		        }
		        
		        // find coordinates to text matches
		        for (i=0;i<ocr_positions.length;i++){
	       			start_index = ocr_positions[i][1][0];
	       			if (start_index in hits){
	       				hits[start_index].box = ocr_positions[i][0]
	       				trace(hits[start_index].box)
	       			}
	       		}
	       		
       		}
       		
       		_base.draw_highlights(hits);
       		
        }
        
					   
	}
}
